package com.ss.project.xia17user.common.mail;

import com.ss.project.xia17user.config.sys.ConfigKey;
import com.ss.project.xia17user.config.sys.SysConfigManager;
import com.ss.project.xia17user.core.exceptions.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * 邮箱配置
 * @author xia17
 * @date 2020/11/24 17:53
 */
@Configuration
@RequiredArgsConstructor
@Slf4j
public class MailConfig {

    private final SysConfigManager sysConfigManager;

    /**
     * 初始化
     */
    @Bean
    public MailSender mailSender(){
        MailSender mailSender = new MailSender();
        if (!sysConfigManager.getConfig(ConfigKey.MAIL_ENABLED).forBoolean()){
            // 未启用
            mailSender.setEnabled(false);
            log.info("未启用邮箱模块");
            return mailSender;
        }
        mailSender.setEnabled(true);
        MailProperties mailProperties = sysConfigManager.getConfig(ConfigKey.MAIL_INFO).forEntity(MailProperties.class);
        if (mailProperties == null){
            throw new BadRequestException("邮箱信息异常");
        }
        // 实例化springboot发送邮件实例
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        // 应用配置
        applyProperties(mailProperties,javaMailSender);
        return mailSender.setJavaMailSender(javaMailSender);
    }


    /**
     * 应用配置
     * @param properties /
     * @param sender /
     */
    private void applyProperties(MailProperties properties, JavaMailSenderImpl sender) {
        sender.setHost(properties.getHost());
        if (properties.getPort() != null) {
            sender.setPort(properties.getPort());
        }
        sender.setUsername(properties.getUsername());
        sender.setPassword(properties.getPassword());
        sender.setProtocol(properties.getProtocol());
        if (properties.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(properties.getDefaultEncoding().name());
        }
    }


}
